home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 19 advanced win32 techniques / win32techniquesdemo / performancecounterform.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  19.1 KB  |  456 lines

  1. Public Class PerformanceCounterForm
  2.     Inherits System.Windows.Forms.Form
  3.  
  4. #Region " Windows Form Designer generated code "
  5.  
  6.     Public Sub New()
  7.         MyBase.New()
  8.  
  9.         'This call is required by the Windows Form Designer.
  10.         InitializeComponent()
  11.  
  12.         'Add any initialization after the InitializeComponent() call
  13.  
  14.     End Sub
  15.  
  16.     'Form overrides dispose to clean up the component list.
  17.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
  18.         If disposing Then
  19.             If Not (components Is Nothing) Then
  20.                 components.Dispose()
  21.             End If
  22.         End If
  23.         MyBase.Dispose(disposing)
  24.     End Sub
  25.     Friend WithEvents txtOut As System.Windows.Forms.TextBox
  26.     Friend WithEvents cboCategories As System.Windows.Forms.ComboBox
  27.     Friend WithEvents Label1 As System.Windows.Forms.Label
  28.     Friend WithEvents Label2 As System.Windows.Forms.Label
  29.     Friend WithEvents cboCounters As System.Windows.Forms.ComboBox
  30.     Friend WithEvents cboInstances As System.Windows.Forms.ComboBox
  31.     Friend WithEvents Label3 As System.Windows.Forms.Label
  32.     Friend WithEvents btnSysinfo As System.Windows.Forms.Button
  33.     Friend WithEvents btnGetCategories As System.Windows.Forms.Button
  34.     Friend WithEvents btnSamples As System.Windows.Forms.Button
  35.     Friend WithEvents btnCreate As System.Windows.Forms.Button
  36.     Friend WithEvents btnDestroy As System.Windows.Forms.Button
  37.     Friend WithEvents btnDisplay As System.Windows.Forms.Button
  38.  
  39.     'Required by the Windows Form Designer
  40.     Private components As System.ComponentModel.Container
  41.  
  42.     'NOTE: The following procedure is required by the Windows Form Designer
  43.     'It can be modified using the Windows Form Designer.  
  44.     'Do not modify it using the code editor.
  45.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  46.         Me.Label3 = New System.Windows.Forms.Label()
  47.         Me.txtOut = New System.Windows.Forms.TextBox()
  48.         Me.btnSamples = New System.Windows.Forms.Button()
  49.         Me.btnGetCategories = New System.Windows.Forms.Button()
  50.         Me.btnSysinfo = New System.Windows.Forms.Button()
  51.         Me.cboCounters = New System.Windows.Forms.ComboBox()
  52.         Me.cboCategories = New System.Windows.Forms.ComboBox()
  53.         Me.btnCreate = New System.Windows.Forms.Button()
  54.         Me.btnDestroy = New System.Windows.Forms.Button()
  55.         Me.cboInstances = New System.Windows.Forms.ComboBox()
  56.         Me.Label1 = New System.Windows.Forms.Label()
  57.         Me.Label2 = New System.Windows.Forms.Label()
  58.         Me.btnDisplay = New System.Windows.Forms.Button()
  59.         Me.SuspendLayout()
  60.         '
  61.         'Label3
  62.         '
  63.         Me.Label3.Location = New System.Drawing.Point(160, 120)
  64.         Me.Label3.Name = "Label3"
  65.         Me.Label3.Size = New System.Drawing.Size(184, 16)
  66.         Me.Label3.TabIndex = 3
  67.         Me.Label3.Text = "Instances"
  68.         '
  69.         'txtOut
  70.         '
  71.         Me.txtOut.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
  72.                     Or System.Windows.Forms.AnchorStyles.Left) _
  73.                     Or System.Windows.Forms.AnchorStyles.Right)
  74.         Me.txtOut.Location = New System.Drawing.Point(160, 184)
  75.         Me.txtOut.Multiline = True
  76.         Me.txtOut.Name = "txtOut"
  77.         Me.txtOut.ScrollBars = System.Windows.Forms.ScrollBars.Both
  78.         Me.txtOut.Size = New System.Drawing.Size(360, 136)
  79.         Me.txtOut.TabIndex = 1
  80.         Me.txtOut.Text = ""
  81.         '
  82.         'btnSamples
  83.         '
  84.         Me.btnSamples.Location = New System.Drawing.Point(16, 64)
  85.         Me.btnSamples.Name = "btnSamples"
  86.         Me.btnSamples.Size = New System.Drawing.Size(120, 40)
  87.         Me.btnSamples.TabIndex = 0
  88.         Me.btnSamples.Text = "Get some samples"
  89.         '
  90.         'btnGetCategories
  91.         '
  92.         Me.btnGetCategories.Location = New System.Drawing.Point(16, 112)
  93.         Me.btnGetCategories.Name = "btnGetCategories"
  94.         Me.btnGetCategories.Size = New System.Drawing.Size(120, 40)
  95.         Me.btnGetCategories.TabIndex = 0
  96.         Me.btnGetCategories.Text = "Get Counter Categories"
  97.         '
  98.         'btnSysinfo
  99.         '
  100.         Me.btnSysinfo.Location = New System.Drawing.Point(16, 16)
  101.         Me.btnSysinfo.Name = "btnSysinfo"
  102.         Me.btnSysinfo.Size = New System.Drawing.Size(120, 40)
  103.         Me.btnSysinfo.TabIndex = 0
  104.         Me.btnSysinfo.Text = "Get some system info"
  105.         '
  106.         'cboCounters
  107.         '
  108.         Me.cboCounters.Anchor = ((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
  109.                     Or System.Windows.Forms.AnchorStyles.Right)
  110.         Me.cboCounters.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
  111.         Me.cboCounters.DropDownWidth = 360
  112.         Me.cboCounters.Location = New System.Drawing.Point(160, 88)
  113.         Me.cboCounters.Name = "cboCounters"
  114.         Me.cboCounters.Size = New System.Drawing.Size(360, 26)
  115.         Me.cboCounters.Sorted = True
  116.         Me.cboCounters.TabIndex = 2
  117.         '
  118.         'cboCategories
  119.         '
  120.         Me.cboCategories.Anchor = ((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
  121.                     Or System.Windows.Forms.AnchorStyles.Right)
  122.         Me.cboCategories.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
  123.         Me.cboCategories.DropDownWidth = 360
  124.         Me.cboCategories.Location = New System.Drawing.Point(160, 32)
  125.         Me.cboCategories.Name = "cboCategories"
  126.         Me.cboCategories.Size = New System.Drawing.Size(360, 26)
  127.         Me.cboCategories.Sorted = True
  128.         Me.cboCategories.TabIndex = 2
  129.         '
  130.         'btnCreate
  131.         '
  132.         Me.btnCreate.Location = New System.Drawing.Point(16, 160)
  133.         Me.btnCreate.Name = "btnCreate"
  134.         Me.btnCreate.Size = New System.Drawing.Size(120, 40)
  135.         Me.btnCreate.TabIndex = 0
  136.         Me.btnCreate.Text = "Create custom counters"
  137.         '
  138.         'btnDestroy
  139.         '
  140.         Me.btnDestroy.Location = New System.Drawing.Point(16, 256)
  141.         Me.btnDestroy.Name = "btnDestroy"
  142.         Me.btnDestroy.Size = New System.Drawing.Size(120, 40)
  143.         Me.btnDestroy.TabIndex = 0
  144.         Me.btnDestroy.Text = "Destroy custom conters"
  145.         '
  146.         'cboInstances
  147.         '
  148.         Me.cboInstances.Anchor = ((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
  149.                     Or System.Windows.Forms.AnchorStyles.Right)
  150.         Me.cboInstances.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
  151.         Me.cboInstances.DropDownWidth = 360
  152.         Me.cboInstances.Location = New System.Drawing.Point(160, 144)
  153.         Me.cboInstances.Name = "cboInstances"
  154.         Me.cboInstances.Size = New System.Drawing.Size(360, 26)
  155.         Me.cboInstances.Sorted = True
  156.         Me.cboInstances.TabIndex = 2
  157.         '
  158.         'Label1
  159.         '
  160.         Me.Label1.Location = New System.Drawing.Point(160, 8)
  161.         Me.Label1.Name = "Label1"
  162.         Me.Label1.Size = New System.Drawing.Size(184, 16)
  163.         Me.Label1.TabIndex = 3
  164.         Me.Label1.Text = "Categories"
  165.         '
  166.         'Label2
  167.         '
  168.         Me.Label2.Location = New System.Drawing.Point(160, 64)
  169.         Me.Label2.Name = "Label2"
  170.         Me.Label2.Size = New System.Drawing.Size(184, 16)
  171.         Me.Label2.TabIndex = 3
  172.         Me.Label2.Text = "Counters"
  173.         '
  174.         'btnDisplay
  175.         '
  176.         Me.btnDisplay.Location = New System.Drawing.Point(16, 208)
  177.         Me.btnDisplay.Name = "btnDisplay"
  178.         Me.btnDisplay.Size = New System.Drawing.Size(120, 40)
  179.         Me.btnDisplay.TabIndex = 0
  180.         Me.btnDisplay.Text = "Display custom counters"
  181.         '
  182.         'PerformanceCounterForm
  183.         '
  184.         Me.AutoScaleBaseSize = New System.Drawing.Size(7, 17)
  185.         Me.ClientSize = New System.Drawing.Size(536, 333)
  186.         Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnDisplay, Me.btnDestroy, Me.btnCreate, Me.btnSamples, Me.cboInstances, Me.Label3, Me.Label2, Me.cboCounters, Me.Label1, Me.cboCategories, Me.btnGetCategories, Me.txtOut, Me.btnSysinfo})
  187.         Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 11!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
  188.         Me.Name = "PerformanceCounterForm"
  189.         Me.Text = "EventLogForm"
  190.         Me.ResumeLayout(False)
  191.  
  192.     End Sub
  193.  
  194. #End Region
  195.  
  196.     ' demonstrates how you can read system info through performance counters
  197.  
  198.     Private Sub btnSysinfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSysinfo.Click
  199.         ' Create a few performance counters.
  200.         Dim pcProcesses As New PerformanceCounter("System", "Processes")
  201.         Dim pcThreads As New PerformanceCounter("System", "Threads")
  202.         Dim pcFilesOpen As New PerformanceCounter("Server", "Files Opened Total")
  203.  
  204.         ' Display their values.
  205.         txtOut.Text = ""
  206.         LogMessage("Processes = " & pcProcesses.RawValue.ToString)
  207.         LogMessage("Threads = " & pcThreads.RawValue.ToString)
  208.         LogMessage("Files Open Total = " & pcFilesOpen.RawValue.ToString)
  209.  
  210.         ' Create specific instances.
  211.         Dim pcHandles As New PerformanceCounter("Process", "Handle Count", "devenv")
  212.         LogMessage("Devenv Handle Count = " & pcHandles.RawValue.ToString)
  213.  
  214.         ' make it point to another instance.
  215.         pcHandles.CounterName = "Thread Count"
  216.         pcHandles.InstanceName = "System"
  217.         LogMessage("System Thread Count = " & pcHandles.RawValue.ToString)
  218.  
  219.         Dim pcDevenvCpuTime As New PerformanceCounter("Process", "% Processor Time", "devenv")
  220.         LogMessage("Devenv % Processor Time = " & pcDevenvCpuTime.NextValue.ToString)
  221.     End Sub
  222.  
  223.     Sub LogMessage(ByVal msg As String)
  224.         txtOut.AppendText(msg & ControlChars.CrLf)
  225.     End Sub
  226.  
  227.     ' demonstrates how you can sample a counter
  228.  
  229.     Private Sub btnSamples_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSamples.Click
  230.         Dim pcSwitches As New PerformanceCounter("Thread", "Context Switches/sec", "_Total")
  231.         ' Read the first sample.
  232.         Dim cs1 As CounterSample = pcSwitches.NextSample
  233.         ' Wait for some time.
  234.         System.Threading.Thread.Sleep(1000)
  235.         ' Read the second sample.
  236.         Dim cs2 As CounterSample = pcSwitches.NextSample
  237.         ' Evaluate the result.
  238.         Dim result As Single = CounterSample.Calculate(cs1, cs2)
  239.         LogMessage("Thread switches/sec = " & result.ToString)
  240.  
  241.         Dim i As Integer
  242.         For i = 1 To 10
  243.             System.Threading.Thread.Sleep(1000)
  244.             ' Get a new sample after one second.
  245.             Dim cs3 As CounterSample = pcSwitches.NextSample
  246.             ' Evaluate "instantaneous" (moving) average.
  247.             result = CounterSample.Calculate(cs2, cs3)
  248.             LogMessage("Thread switches/sec = " & result.ToString)
  249.             ' Evaluate average value since the first sample.
  250.             result = CounterSample.Calculate(cs1, cs3)
  251.             LogMessage("Average Thread switches/sec = " & result.ToString)
  252.             ' Use most recent sample as the basis for next moving average.
  253.             cs2 = cs3
  254.         Next
  255.     End Sub
  256.  
  257.     ' get all the counter categories
  258.  
  259.     Private Sub btnGetCategories_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetCategories.Click
  260.         Dim pcc As PerformanceCounterCategory
  261.  
  262.         cboCategories.Items.Clear()
  263.         ' Store categories in the combobox, but display their name.
  264.         cboCategories.DisplayMember = "CategoryName"
  265.         ' Load the combobox with all category names.
  266.         For Each pcc In PerformanceCounterCategory.GetCategories
  267.             cboCategories.Items.Add(pcc)
  268.         Next
  269.         ' Select the first element.
  270.         cboCategories.SelectedIndex = 0
  271.     End Sub
  272.  
  273.     ' Fill the other two combobox controls when a category is selected.
  274.  
  275.     Private Sub cboCategories_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCategories.SelectedIndexChanged
  276.         Dim pcCat As PerformanceCounterCategory
  277.         Dim pCnt As PerformanceCounter
  278.         Dim instName As String
  279.  
  280.         ' Get a reference to the selected category
  281.         pcCat = CType(cboCategories.SelectedItem, PerformanceCounterCategory)
  282.  
  283.         ' Fill cboCounters with the list of counters.
  284.         cboCounters.Items.Clear()
  285.         ' Get a collection of counters for this category
  286.         Dim idcc As InstanceDataCollectionCollection = pcCat.ReadCategory
  287.  
  288.         ' Each element of this collection is associated with a counter.
  289.         Dim cntName As String
  290.         For Each cntName In idcc.Keys
  291.             cboCounters.Items.Add(cntName)
  292.         Next
  293.  
  294.         ' Fill cboInstances with the list of instances.
  295.         cboInstances.Items.Clear()
  296.         cboInstances.Items.Add("(all)")
  297.         Try
  298.             For Each instName In pcCat.GetInstanceNames
  299.                 cboInstances.Items.Add(instName)
  300.             Next
  301.         Catch ex As Exception
  302.             ' nothing to do - ignore the error
  303.         End Try
  304.  
  305.         ' select the first element in both comboboxes
  306.         If cboCounters.Items.Count > 0 Then
  307.             cboCounters.SelectedIndex = 0
  308.         End If
  309.         If cboInstances.Items.Count > 0 Then
  310.             cboInstances.SelectedIndex = 0
  311.         End If
  312.     End Sub
  313.  
  314.     ' refresh display when a new counter/instance is selected
  315.  
  316.     Private Sub CounterInstanceChange(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCounters.SelectedIndexChanged, cboInstances.SelectedIndexChanged
  317.         ' Create the array of 1 or more PerformanceCounter objects
  318.         Dim catName As String = CType(cboCategories.SelectedItem, PerformanceCounterCategory).CategoryName
  319.         Dim cntName As String = cboCounters.SelectedItem.ToString
  320.  
  321.         ' Two cases
  322.  
  323.         If cboInstances.SelectedIndex > 0 Then
  324.             ' One single instance
  325.             Dim instName As String = cboInstances.SelectedItem.ToString
  326.             ReDim counters(0)
  327.             counters(0) = New PerformanceCounter(catName, cntName, instName)
  328.         Else
  329.             ' Multiple instances
  330.             Dim pcCat As PerformanceCounterCategory
  331.             pcCat = CType(cboCategories.SelectedItem, PerformanceCounterCategory)
  332.             Dim instNames() As String = pcCat.GetInstanceNames
  333.             ReDim counters(instNames.GetUpperBound(0))
  334.             Dim i As Integer
  335.             For i = 0 To UBound(counters)
  336.                 counters(i) = New PerformanceCounter(catName, cntName, instNames(i))
  337.             Next
  338.         End If
  339.  
  340.         RefreshValues()
  341.  
  342.     End Sub
  343.  
  344.     ' The list of counters to be refreshed
  345.     Dim counters() As PerformanceCounter
  346.     Dim samples() As CounterSample
  347.  
  348.     ' update the display of selected counters/instances
  349.     Private Sub RefreshValues()
  350.         Dim sb As New System.Text.StringBuilder(1000)
  351.         Dim pCnt As PerformanceCounter
  352.  
  353.         ' Get the list of values
  354.         For Each pCnt In counters
  355.             sb.Append(pCnt.InstanceName)
  356.             sb.Append(" = ")
  357.             sb.Append(GetCounterValue(pCnt))
  358.             sb.Append(ControlChars.CrLf)
  359.         Next
  360.  
  361.         ' Display in textbox
  362.         txtOut.Text = sb.ToString
  363.     End Sub
  364.  
  365.     ' Get the value of a given PerformanceCounter object
  366.  
  367.     Private Function GetCounterValue(ByVal pCnt As PerformanceCounter) As String
  368.         Select Case pCnt.CounterType
  369.             Case PerformanceCounterType.NumberOfItems32, PerformanceCounterType.NumberOfItems64
  370.                 Return pCnt.RawValue.ToString
  371.             Case PerformanceCounterType.RateOfCountsPerSecond32, PerformanceCounterType.RateOfCountsPerSecond64
  372.                 Return pCnt.NextValue.ToString
  373.             Case PerformanceCounterType.AverageTimer32
  374.                 Return pCnt.NextValue.ToString
  375.         End Select
  376.     End Function
  377.  
  378.     ' create a new performance counter
  379.  
  380.     Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
  381.         Dim counters As New CounterCreationDataCollection()
  382.         Dim ccd As CounterCreationData
  383.  
  384.         ' Exit if the category exists already.
  385.         If PerformanceCounterCategory.Exists("MyApp") Then
  386.             Exit Sub
  387.         End If
  388.  
  389.         ' Define the first counter, then add it to the collection.
  390.         ccd = New CounterCreationData("Flush operations", "Total number of flush operations", PerformanceCounterType.NumberOfItems32)
  391.         counters.Add(ccd)
  392.  
  393.         ' Define the second counter, then add it to the collection.
  394.         ccd = New CounterCreationData("Flush operations / sec", "Number of flush operations per second", PerformanceCounterType.RateOfCountsPerSecond32)
  395.         counters.Add(ccd)
  396.  
  397.         ' Create the category and the counters in one operation.
  398.         PerformanceCounterCategory.Create("MyApp", "Counters for MyApp program", counters)
  399.     End Sub
  400.  
  401.     ' generate some custom values
  402.  
  403.     Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
  404.         Dim pc1 As New PerformanceCounter("MyApp", "Flush operations", False)
  405.         Dim pc2 As New PerformanceCounter("MyApp", "Flush operations / sec", False)
  406.         Dim res As Single
  407.         txtOut.Text = ""
  408.  
  409.         ' Assign a starting value.
  410.         pc1.RawValue = 10
  411.         pc2.RawValue = 10
  412.         ' store an initial sample.
  413.         Dim cs1 As CounterSample = pc2.NextSample
  414.  
  415.         ' Wait some time and increment values.
  416.         System.Threading.Thread.Sleep(500)
  417.         pc1.IncrementBy(15)
  418.         pc2.IncrementBy(15)
  419.         ' Display current values
  420.         res = CounterSample.Calculate(cs1, pc2.NextSample)
  421.         LogMessage("Flush operations = " & pc1.RawValue.ToString)
  422.         LogMessage("Flush operations / sec = " & res.ToString)
  423.  
  424.         ' Wait some time and increment values.
  425.         System.Threading.Thread.Sleep(500)
  426.         pc1.IncrementBy(25)
  427.         pc2.IncrementBy(25)
  428.         ' Display current values
  429.         res = CounterSample.Calculate(cs1, pc2.NextSample)
  430.         LogMessage("Flush operations = " & pc1.RawValue.ToString)
  431.         LogMessage("Flush operations / sec = " & res.ToString)
  432.  
  433.         Dim pc3 As New PerformanceCounter("MyApp", "Flush operations", False)
  434.         ' Create a first instance.
  435.         pc3.InstanceName = "First"
  436.         pc3.RawValue = 10
  437.         ' Create a second instance.
  438.         pc3.InstanceName = "Second"
  439.         pc3.RawValue = 20
  440.         ' Display the value of the two instances.
  441.         pc3.InstanceName = "First"
  442.         Debug.WriteLine("First Instance = " & pc3.RawValue.ToString)
  443.         pc3.InstanceName = "Second"
  444.         Debug.WriteLine("Second Instance = " & pc3.RawValue.ToString)
  445.     End Sub
  446.  
  447.     ' Destroy the custom category built previously.
  448.  
  449.     Private Sub btnDestroy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDestroy.Click
  450.         ' check whether the category exists.
  451.         If PerformanceCounterCategory.Exists("MyApp") Then
  452.             PerformanceCounterCategory.Delete("MyApp")
  453.         End If
  454.     End Sub
  455. End Class
  456.